<template>
  <div class="patients-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>患者信息管理</span>
          <el-button type="primary" @click="showAddPatientDialog">添加患者</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="患者姓名">
            <el-input 
              v-model="searchForm.patient_name" 
              placeholder="请输入患者姓名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input 
              v-model="searchForm.id_card" 
              placeholder="请输入身份证号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select 
              v-model="searchForm.gender" 
              placeholder="请选择性别"
              clearable
            >
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <el-table 
        v-loading="loading" 
        :data="paginatedPatients" 
        style="width: 100%"
        border
      >
        <el-table-column prop="patient_id" label="患者ID" width="80" />
        <el-table-column prop="patient_name" label="姓名" width="120" />
        <el-table-column prop="id_card" label="身份证号" width="180" />
        <el-table-column prop="gender" label="性别" width="80" />
        <el-table-column prop="birth_date" label="出生日期" width="120" />
        <el-table-column prop="phone_number" label="联系电话" width="150" />
        <el-table-column prop="address" label="住址" width="200" />
        <el-table-column prop="blood_type" label="血型" width="80" />
        <el-table-column prop="allergies" label="过敏史" width="150" />
        <el-table-column prop="creation_time" label="创建时间" width="150" />
        <el-table-column label="操作" width="150" fixed="right">
      <template #default="{ row }">
        <!-- 确保正确获取患者ID，处理不同格式的字段名 -->
        <el-button 
          type="primary" 
          size="small" 
          :disabled="!row.patient_id"
          @click="viewPatientDetail(row.patient_id)"
        >详情</el-button>
        <el-button type="warning" size="small" @click="editPatient(row)">编辑</el-button>
        <el-button type="danger" size="small" @click="deletePatient(row.patient_id)">删除</el-button>
      </template>
    </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="patients.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑患者对话框 -->
    <el-dialog
      v-model="patientDialogVisible"
      :title="dialogType === 'add' ? '添加患者' : '编辑患者'"
      width="700px"
    >
      <el-form 
        :model="patientForm" 
        ref="patientFormRef" 
        label-width="120px"
        :rules="formRules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="患者姓名" prop="patient_name">
              <el-input v-model="patientForm.patient_name" placeholder="请输入患者姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="id_card">
              <el-input v-model="patientForm.id_card" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="patientForm.gender" placeholder="请选择性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birth_date">
              <el-date-picker
                v-model="patientForm.birth_date"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone_number">
              <el-input v-model="patientForm.phone_number" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="血型" prop="blood_type">
              <el-select v-model="patientForm.blood_type" placeholder="请选择血型">
                <el-option label="A" value="A"></el-option>
                <el-option label="B" value="B"></el-option>
                <el-option label="AB" value="AB"></el-option>
                <el-option label="O" value="O"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="住址" prop="address">
              <el-input 
                v-model="patientForm.address" 
                placeholder="请输入住址"
                type="textarea"
                rows="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="过敏史" prop="allergies">
              <el-input 
                v-model="patientForm.allergies" 
                placeholder="请输入过敏史，如无请填写'无'"
                type="textarea"
                rows="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="既往病史" prop="past_history">
              <el-input 
                v-model="patientForm.past_history" 
                placeholder="请输入既往病史，如无请填写'无'"
                type="textarea"
                rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="patientDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPatientForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { patientAPI } from '../api'

const router = useRouter()

// 状态数据
const loading = ref(false)
const patients = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const searchForm = ref({
  patient_name: '',
  id_card: '',
  gender: ''
})

// 对话框相关
const patientDialogVisible = ref(false)
const dialogType = ref('add')
const patientFormRef = ref()
const patientForm = ref({
  patient_id: '',
  patient_name: '',
  id_card: '',
  gender: '',
  birth_date: '',
  phone_number: '',
  address: '',
  blood_type: '',
  allergies: '',
  past_history: ''
})

// 表单验证规则
const formRules = {
  patient_name: [
    { required: true, message: '请输入患者姓名', trigger: 'blur' }
  ],
  id_card: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: '请输入有效的身份证号',
      trigger: 'blur'
    }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birth_date: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  phone_number: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号码',
      trigger: 'blur'
    }
  ]
}

// 过滤后的患者列表
const filteredPatients = computed(() => {
  let result = [...patients.value]
  
  // 根据搜索条件过滤
  if (searchForm.value.patient_name) {
    result = result.filter(patient => 
      patient.patient_name && patient.patient_name.includes(searchForm.value.patient_name)
    )
  }
  
  if (searchForm.value.id_card) {
    result = result.filter(patient => 
      patient.id_card && patient.id_card.includes(searchForm.value.id_card)
    )
  }
  
  if (searchForm.value.gender) {
    result = result.filter(patient => 
      patient.gender === searchForm.value.gender
    )
  }
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 获取患者列表
const getPatients = async () => {
  loading.value = true
  try {
    const data = await patientAPI.getPatients()
    // 规范化患者数据格式，确保字段名一致
    patients.value = data.map(item => ({
      patient_id: item.patient_id || item['患者ID'],
      patient_name: item.patient_name || item['姓名'],
      id_card: item.id_card || item['身份证号'],
      gender: item.gender || item['性别'],
      birth_date: item.birth_date || item['出生日期'],
      phone_number: item.phone_number || item['联系方式'],
      address: item.address || item['常住地址'],
      blood_type: item.blood_type || item['血型'] || '未知',
      allergies: item.allergies || item['过敏史'] || '无',
      past_history: item.past_history || item['既往病史'] || '无',
      creation_time: new Date(item.created_at || item['created_at']).toLocaleString()
    }))
  } catch (error) {
    ElMessage.error('获取患者列表失败')
    console.error('获取患者列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取患者列表
onMounted(() => {
  getPatients()
})

// 搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    patient_name: '',
    id_card: '',
    gender: ''
  }
  currentPage.value = 1
}

// 计算过滤后且分页的患者列表
const paginatedPatients = computed(() => {
  const filtered = filteredPatients.value
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 显示添加患者对话框
const showAddPatientDialog = () => {
  dialogType.value = 'add'
  patientForm.value = {
    patient_id: '',
    patient_name: '',
    id_card: '',
    gender: '',
    birth_date: '',
    phone_number: '',
    address: '',
    blood_type: '',
    allergies: '',
    past_history: ''
  }
  patientDialogVisible.value = true
}

// 编辑患者
const editPatient = (row) => {
  dialogType.value = 'edit'
  patientForm.value = { ...row }
  patientDialogVisible.value = true
}

// 提交表单
const submitPatientForm = async () => {
  try {
    await patientFormRef.value.validate()
    
    if (dialogType.value === 'add') {
      // 生成患者ID
      const newPatient = {
        ...patientForm.value,
        patient_id: Date.now(), // 简单生成ID
        creation_time: new Date().toISOString()
      }
      
      await patientAPI.addPatient(newPatient)
      ElMessage.success('患者添加成功')
    } else {
      await patientAPI.updatePatient(patientForm.value)
      ElMessage.success('患者信息更新成功')
    }
    
    patientDialogVisible.value = false
    getPatients() // 重新获取列表
  } catch (error) {
    if (error !== false) { // 非表单验证错误
      ElMessage.error('操作失败，请重试')
      console.error('操作失败:', error)
    }
  }
}

// 删除患者
const deletePatient = async (patientId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该患者信息吗？此操作不可撤销！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await patientAPI.deletePatient(patientId)
    ElMessage.success('患者信息已删除')
    getPatients() // 重新获取列表
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }
}

// 查看患者详情
const viewPatientDetail = (patientId) => {
  if (patientId) {
    // 确保患者ID是数字类型
    const numPatientId = parseInt(patientId)
    if (!isNaN(numPatientId)) {
      router.push(`/patients/${numPatientId}`)
      console.log(`导航到患者详情页面，ID: ${numPatientId}`)
    } else {
      ElMessage.warning('患者ID格式不正确')
    }
  } else {
    ElMessage.warning('患者ID无效')
  }
}

// 组件挂载时获取患者列表
onMounted(() => {
  getPatients()
})
</script>

<style scoped>
.patients-container {
  padding: 20px;
  background-color: #FFFFFF;
  min-height: 100vh;
}

.page-card {
  margin-bottom: 20px;
  background-color: #FFFFFF;
  border: 1px solid #e0e0e0;
  box-shadow: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000000;
}

/* 确保文字为黑色 */
.card-header span {
  color: #000000 !important;
  border: none !important;
  background: none !important;
}

.search-filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #FFFFFF;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  box-shadow: none;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格样式 */
:deep(.el-table) {
  --el-table-bg-color: #FFFFFF;
  --el-table-header-bg-color: #f5f5f5;
  --el-table-border-color: #e0e0e0;
  --el-table-text-color: #000000;
}

:deep(.el-table thead) {
  --el-table-header-cell-text-color: #000000;
}

:deep(.el-table tbody) {
  --el-table-row-hover-bg-color: #f5f5f5;
  --el-table-row-current-bg-color: #e6f7ff;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  color: #000000;
}

:deep(.el-input__wrapper) {
  background-color: #FFFFFF;
  border-color: #dcdfe6;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
}

:deep(.el-input__inner) {
  color: #000000;
}

:deep(.el-input__placeholder) {
  color: #909399;
}

:deep(.el-select__wrapper) {
  background-color: #FFFFFF;
  border-color: #dcdfe6;
}

:deep(.el-select__wrapper:hover) {
  border-color: #409eff;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
}

:deep(.el-select__inner) {
  color: #000000;
}

:deep(.el-select__placeholder) {
  color: #909399;
}

/* 对话框样式 */
:deep(.el-dialog__title) {
  color: #000000;
}

:deep(.el-dialog__body) {
  background-color: #FFFFFF;
  color: #000000;
}

:deep(.el-dialog__footer) {
  background-color: #FFFFFF;
  border-top: 1px solid #e0e0e0;
}

:deep(.el-date-editor .el-input__wrapper) {
  background-color: #FFFFFF;
  border-color: #dcdfe6;
}

:deep(.el-date-editor .el-input__inner) {
  color: #000000;
}

/* 分页组件样式 */
:deep(.el-pagination__total) {
  color: #000000;
}

:deep(.el-pagination__sizes .el-input__wrapper) {
  background-color: #FFFFFF;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-bottom: 10px;
  }
}

@media (max-width: 768px) {
  .patients-container {
    padding: 10px;
  }
  
  .pagination-container {
    justify-content: center;
  }
  
  .el-button {
    font-size: 12px;
    padding: 6px 12px;
  }
}
</style>